﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Net;

namespace Magic.Core;

/// <summary>
/// 全局异常捕获
/// </summary>
public class GlobalExceptionFilter : IAsyncExceptionFilter
{
    public async Task OnExceptionAsync(ExceptionContext context)
    {
        if (IsWebSocketRequest(context.HttpContext)) return;

        if (context.ExceptionHandled) return;
        context.Result = new JsonResult(new RestfulResult<object>
        {
            Code = context.Exception is ApiException ? StatusCodes.Status400BadRequest : StatusCodes.Status500InternalServerError,
            Success = false,
            Data = null,
            Msg = context.Exception.Message,
            Timestamp = DateTime.Now.Millisecond
        });

    }

    /// <summary>
    /// 判断是否是 WebSocket 请求
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private bool IsWebSocketRequest(HttpContext context)
    {
        return context.WebSockets.IsWebSocketRequest || context.Request.Path == "/ws";
    }
}
